package com.liuweidihuangwan.jingdong.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.liuweidihuangwan.jingdong.common.BaseResponse;
import com.liuweidihuangwan.jingdong.common.ResultUtils;
import com.liuweidihuangwan.jingdong.model.dto.shangpin.ShangpinAddRequest;
import com.liuweidihuangwan.jingdong.model.dto.shangpin.ShangpinQueryRequest;
import com.liuweidihuangwan.jingdong.model.entity.Image;
import com.liuweidihuangwan.jingdong.model.entity.Shangpin;
import com.liuweidihuangwan.jingdong.model.vo.ShangpinVO;
import com.liuweidihuangwan.jingdong.service.ImageService;
import com.liuweidihuangwan.jingdong.service.ShangpinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-01-08
 */
@RestController
@RequestMapping("/shangpin")
@Api(tags = "商品相关接口")
public class ShangpinController {

    @Resource
    ShangpinService shangpinService;

    @Resource
    ImageService imageService;

    @GetMapping("/list")
    @ApiOperation("查条件查询商品")
    BaseResponse<List<ShangpinVO>> queryShangpinList(ShangpinQueryRequest shangpinQueryRequest){
        List<ShangpinVO> shangpinVOS = shangpinService.queryShangpinList(shangpinQueryRequest);

        return ResultUtils.success(shangpinVOS);
    }

    @GetMapping("/add/batch")
    @ApiOperation("批量新增商品图片接口")
    BaseResponse<List<String>> addShangpinBatch(ShangpinAddRequest shangpinAddRequest){
        String searchText = shangpinAddRequest.getName();
        String fetchUrl = String.format("https://cn.bing.com/images/search?q=%s&mmasync=1",searchText);
        int pictureCount = 0;
        List<String> imgSrcs = new ArrayList<>();
        try {
            Document doc = Jsoup.connect(fetchUrl).get();
            //解析内容
            for (Element img : doc.select("img.mimg")) {
                pictureCount ++;
                if(pictureCount > 5){
                    break;
                }
                // Extract the src attribute
                String imgSrc = img.attr("src");
                imgSrcs.add(imgSrc);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Shangpin shangpin = new Shangpin();
        BeanUtils.copyProperties(shangpinAddRequest,shangpin);
        shangpin.setImg(imgSrcs.get(0));
        shangpinService.save(shangpin);

        Integer spID = shangpin.getSpID();
        List<Image> images = new ArrayList<>();
        for (String imgSrc : imgSrcs) {
            Image img = new Image();
            img.setSrc(imgSrc);
            img.setTypes(2);
            img.setKindID(spID);
            imageService.save(img);
        }

        return ResultUtils.success(imgSrcs);
    }


    @GetMapping("/add/batch/shangpin")
    @ApiOperation("批量添加商品接口")
    BaseResponse<List<Shangpin>> getShangpinBatch(String searchText){

        String fetchUrl = String.format("https://re.m.jd.com/search?keyword=%s",searchText);

        List<Shangpin> shangpins = new ArrayList<>();
        try {
            Document doc = Jsoup.connect(fetchUrl).get();
            // Find the script element containing the configs variable
            Element scriptElement = doc.select("script").stream()
                    .filter(script -> script.html().contains("var configs = {"))
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("Script element containing configs not found"));

            // Extract the script content
            String scriptContent = scriptElement.html();

            // Extract the JSON part from the script content
            String jsonString = scriptContent.substring(scriptContent.indexOf("{"), scriptContent.lastIndexOf("};") + 1);

            // Parse the JSON string
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray dataArray = jsonObject.getJSONArray("moduleInfo").getJSONObject(0).getJSONArray("data");

            // Iterate over the data array and print title and imageUrl
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject dataObject = dataArray.getJSONObject(i);
                String title = dataObject.getStr("title");
                String imageUrl = dataObject.getStr("imageUrl");
                System.out.println("Title: " + title);
                System.out.println("ImageUrl: " + imageUrl);
                String price = dataObject.getStr("price");
                Shangpin shangpin = new Shangpin();
                shangpin.setName(title);
                shangpin.setImg("https://m.360buyimg.com/n6/"+imageUrl);
                shangpin.setIntroduce(title);
                shangpin.setPrice(new BigDecimal(price));
                shangpin.setSalesNum(200);
                shangpin.setRepertory(200);
                shangpin.setLabelID(1);
                shangpinService.save(shangpin);
                shangpins.add(shangpin);

            }
        } catch (IOException | JSONException e) {
            throw new RuntimeException(e);
        }
        return ResultUtils.success(shangpins);
    }

}
